#include <stdio.h>
#include <unistd.h>
#include <aio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#define BUFFSIZE 1024
#define AIO_LIST_NUM 2

int r;
int fd;
int fd1;
struct aiocb cb = {0};
struct aiocb cb1 = {0};

void hand(int s)
{
    printf("收到信号:%d\n",s);
    switch (s)
    {
    case 2:
        r = aio_return(&cb);
        if (r >0)
        {
            printf("读到了%d字节数据:%s\n",r,cb.aio_buf);
        }

        int r1 = aio_return(&cb1);
        if (r1 >0)
        {
            printf("读到了%d字节数据:%s\n",r1,cb1.aio_buf);
        }
        //收尾
        free(cb.aio_buf);
        free(cb1.aio_buf);
        close(fd);
        close(fd1);

        break;
    }
}

int main()
{
    //准备好缓冲区
    signal(2,hand);
    signal(3,hand);

    //异步读
     fd = open("1.txt",O_RDONLY);
    if (-1==fd)
    {
        printf("打开文件失败:%m\n");
        exit(-1);
    }
    printf("打开文件成功\n");


     fd1 = open("2.txt",O_RDONLY);
    if (-1==fd1)
    {
        printf("打开文件失败:%m\n");
        exit(-1);
    }
    printf("打开文件成功\n");



    cb.aio_fildes = fd;
    cb.aio_offset=0;//偏移量
    cb.aio_buf = malloc(BUFFSIZE);
    memset(cb.aio_buf,0,BUFFSIZE);
    cb.aio_nbytes = BUFFSIZE-1;
    // cb.aio_reqprio = 0;


    cb1.aio_fildes = fd1;
    cb1.aio_offset=0;//偏移量
    cb1.aio_buf = malloc(BUFFSIZE);
    memset(cb1.aio_buf,0,BUFFSIZE);
    cb1.aio_nbytes = BUFFSIZE-1;


     r = aio_read(&cb);
    if (-1==r)
    {
        printf("异步读失败:%m\n");
        exit(-1);
    }
    printf("异步读成功\n");

    r = aio_read(&cb1);
    if (-1==r)
    {
        printf("异步读失败:%m\n");
        exit(-1);
    }
    printf("异步读成功\n");


    //检查是否操作完毕
    struct aiocb* aiocb_list[AIO_LIST_NUM];
    aiocb_list[0] = &cb;
    aiocb_list[0] = &cb1;

    struct sigevent s={0};
    s.sigev_notify=SIGEV_SIGNAL;
    s.sigev_value.sival_int=666;
    s.sigev_signo=2;

    struct sigevent* ev[AIO_LIST_NUM]={0};

    ev[0]=&s;

    struct sigevent s1={0};
    s1.sigev_notify=SIGEV_SIGNAL;
    s1.sigev_value.sival_int=666;
    s1.sigev_signo=3;


    ev[1]=&s1;

    printf("abc\n");

    r = lio_listio(LIO_NOWAIT,aiocb_list,AIO_LIST_NUM,ev); //有一个就返回
    if (-1==r)
    {
        printf("lio_listio失败:%m\n");
        exit(-1);
    }
    printf("lio_listio结束\n");

    int n=0;
    //得到数据
    while (1)
    {
       printf("n=:%d\n",n++);
        sleep(1);
    }


    return 0;
}